<?php


//验证验证码
function check_captcha($input_captcha)
{
    if ($input_captcha) {
        $seccode = session('seccode');
        if (strtoupper($input_captcha) == $seccode) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

//生成验证码
function generate_captcha()
{
    ob_clean();
    $seccode = makeSeccode();
    $code = new \App\Support\seccode();
    $code->code = $seccode;
    $code->width = 90;
    $code->height = 26;
    $code->background = 1;
    $code->adulterate = 1;
    $code->scatter = '';
    $code->color = 1;
    $code->size = 0;
    $code->shadow = 1;
    $code->animator = 0;
    $code->datapath = 'seccode/';
    return response($code->display())->header('Content-Type', 'image/jpeg');
}

function makeSeccode()
{
    $seccode = random(6, 1);
    $seccodeunits = '';

    $s = sprintf('%04s', base_convert($seccode, 10, 23));
    $seccodeunits = 'ABCEFGHJKMPRTVXY2346789';
    if ($seccodeunits) {
        $seccode = '';
        for ($i = 0; $i < 4; $i++) {
            $unit = ord($s{$i});
            $seccode .= ($unit >= 0x30 && $unit <= 0x39) ? $seccodeunits[$unit - 0x30] : $seccodeunits[$unit - 0x57];
        }
    }
    session(['seccode' => $seccode]);
    return $seccode;
}

function random($length, $numeric = 0)
{
    $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
    $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
    $hash = '';
    $max = strlen($seed) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $seed{mt_rand(0, $max)};
    }
    return $hash;
}

//trim单个或数组中的字符串
function trim_fileds($inputs)
{
    $params = '';
    if (is_array($inputs)) {
        foreach ($inputs as $k => $v) {
            $params[$k] = trim($v);
        }
    } else {
        $params = trim($inputs);
    }
    return $params;
}

/*闪存重定向
 * $url       重定向地址
 *$message    提示信息
 *$type       提示类别，1不带原始提交的参数，2携带原始提交的参数
 * 跳转的页面用session接收传递的参数message
 */
function show_message($url, $message, $type = 1)
{
    if ($type == 2) {
        return redirect($url)->with('message', $message)->withInput();
    } else {
        return redirect($url)->with('message', $message);
    }
}


function getRandNum($length = 6)
{
    $key = '';
    $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
    for ($i = 0; $i < $length; $i++) {
        $key .= $pattern{mt_rand(0, 35)};    //生成php随机数
    }
    return $key;
}

//重新加密
function setMd5ByMark($password, $mark = '')
{
    return md5(md5($password) . $mark);

}

/*替换集合中某字段的值为另一集合中的值
 *$collection       被替换集合
 *$textArr    目标集合
 *$name       被替换集合中的字段名
 *$replaceName       目标集合中字段名
 */
function replace_field($collection, $textArr, $name, $replaceName)
{
    foreach ($collection as $col) {
        foreach ($textArr as $text) {
            if ($col->$name == $text->$name) {
                $col->$name = $text->$replaceName;
            }
        }
    }
}


if (!function_exists('msubstr')) {
    /**
     * 字符截取,支持中英文
     *
     * @param $str
     * @param int $start
     * @param $length
     * @param string $charset
     * @param bool|true $suffix
     * @return string
     * author zl
     */
    function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
    {
        if (function_exists("mb_substr"))
            return mb_substr($str, $start, $length, $charset);
        elseif (function_exists('iconv_substr')) {
            return iconv_substr($str, $start, $length, $charset);
        }
        $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("", array_slice($match[0], $start, $length));
        if ($suffix) return $slice . "…";
        return $slice;
    }
}


function childTree($res, $myid, $mid, $pid, $level = 0)
{
    static $childs = array();
    foreach ($res as $k => $v) {
        if ($v[$pid] == $myid) {
            $v['prefix'] = $level ? str_repeat('&nbsp;', $level * 4) . '∟&nbsp;' : str_repeat('&nbsp;', $level * 4);
            $childs[] = $v;
            childTree($res, $v[$mid], $mid, $pid, $level + 1);
        }
    }
    return $childs;

}

/** 二维数组无限级分类(找下级)  BY ZJC
 * Array    $m     需要递归查询的结果集
 * String   $name      需要查询下级从属的ID
 * Int      $pid     数据库中ID的字段名
 * return Array   返回循环查找后的二维数组结果
 */
function levelTree($res, $idField, $pidField, $pid = 0)
{
    $arr = array();
    if (empty($res)) {
        return $arr;
    }
    foreach ($res as $v) {
        if ($v[$pidField] == $pid) {
            $v['child'] = levelTree($res, $idField, $pidField, $v[$idField]);
            $arr[] = $v;
        }
    }
    return $arr;
}

//对二维数组进行某个字段的升序排列
function sortArrayAsc($preData, $sortType = 'sort')
{
    $sortData = array();
    foreach ($preData as $key_i => $value_i) {
        $sort_i = $value_i[$sortType];
        $min_key = '';
        $sort_total = count($sortData);
        foreach ($sortData as $key_j => $value_j) {
            if ($sort_i < $value_j[$sortType]) {
                $min_key = $key_j + 1;
                break;
            }
        }
        if (empty($min_key)) {
            array_push($sortData, $value_i);
        } else {
            $sortData1 = array_slice($sortData, 0, $min_key - 1);
            array_push($sortData1, $value_i);
            if (($min_key - 1) < $sort_total) {
                $sortData2 = array_slice($sortData, $min_key - 1);
                foreach ($sortData2 as $value) {
                    array_push($sortData1, $value);
                }
            }
            $sortData = $sortData1;
        }
    }
    return $sortData;
}

function mult_unique($array)
{
    $return = array();
    foreach ($array as $key => $v) {
        if (!in_array($v, $return)) {
            $return[$key] = $v;
        }
    }
    return $return;
}

if (!function_exists('changeArray')) {
    /**
     * @param $arr    查询出来的数组数据
     * @param $field  作为数组键的字段名
     * 转换数组键值
     */
    function changeArray($arr, $field)
    {
        $data = array();
        foreach ($arr as $key => $item) {
            $data[$item[$field]] = $item;
        }
        return $data;
    }
}
/***
 * 生成订单号
 */
if (!function_exists('createOrderNo')) {
    function createOrderNo()
    {
        list($tmp1, $tmp2) = explode(' ', microtime());
        $msec = (int)sprintf('%.0f', (floatval($tmp1) + floatval($tmp2)) * 1000);
        return $msec;
    }
}


if (!function_exists('upload')) {
    /**
     * 图片上传
     *
     * @return \App\Support\Uploads\Upload
     * author zl <178417451@qq.com>
     */
    function upload()
    {
        $upload = new App\Support\Uploads\Upload();
        return $upload;
    }
}

if (!function_exists('articleCategorySelect')) {
    /**
     * 文章分类选择
     *
     * @return \App\Support\Uploads\Upload
     * author zl <178417451@qq.com>
     */
    function articleCategorySelect($id = '')
    {
        $category = new \App\Models\ArticleCategory();
        return $category->caregorySelect($id);
    }
}

if (!function_exists('getSysBasicInfo')) {
    function getSysBasicInfo()
    {
        $info = [];
        $info['sysos'] = $_SERVER["SERVER_SOFTWARE"];      //获取服务器标识的字串
        $info['os'] = PHP_OS;
        $info['sysversion'] = PHP_VERSION;                   //获取PHP服务器版本
        //从服务器中获取GD库的信息
        if (function_exists("gd_info")) {
            $gd = gd_info();
            $info['gdinfo'] = $gd['GD Version'];
        } else {
            $info['gdinfo'] = "未知";
        }
        //从PHP配置文件中获得是否可以远程文件获取
        $info['allowurl'] = ini_get("allow_url_fopen") ? "支持" : "不支持";
        //从PHP配置文件中获得最大上传限制
        $info['max_upload'] = ini_get("file_uploads") ? ini_get("upload_max_filesize") : "Disabled";
        //从PHP配置文件中获得脚本的最大执行时间
        $info['max_ex_time'] = ini_get("max_execution_time") . "秒";
        //以下两条获取服务器时间，中国大陆采用的是东八区的时间,设置时区写成Etc/GMT-8
        date_default_timezone_set("Etc/GMT-8");
        $info['systemtime'] = date("Y-m-d H:i:s", time());
        return $info;
    }

}


function object_array($array)
{
    if (is_object($array)) {
        $array = (array)$array;
    }
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            $array[$key] = object_array($value);
        }
    }
    return $array;
}


/**
 * 后台使用的URL链接函数，强制使用动态传参数模式
 *
 * @param string $controller control文件名
 * @param string $method op方法名
 * @param array $args URL其它参数
 * @param array $type URL模式  1./参数模式   2.?参数模式
 * @return string
 */
function urlAdmin($controller, $method, $args = [], $type = 1)
{
    $controller = ucfirst($controller);
    if ($type == 2) {
        if ($args && is_array($args)) {
            return action("Admin\\{$controller}Controller@$method") . '?' .
            http_build_query($args);
        }
    }
    if ($args && is_array($args)) {
        return action("Admin\\{$controller}Controller@$method", $args);
    }
    return action("Admin\\{$controller}Controller@$method");
}

function urlHome($controller, $method, $args = [], $type = 1)
{
    $controller = ucfirst($controller);
    if ($type == 2) {
        if ($args && is_array($args)) {
            return action("Home\\{$controller}Controller@$method") . '?' .
            http_build_query($args);
        }
    }
    if ($args && is_array($args)) {
        return action("Home\\{$controller}Controller@$method", $args);
    }
    return action("Home\\{$controller}Controller@$method");
}

function ajaxReturn($data)
{
    return response()->json($data);
}

/**
 * 浏览器友好的变量输出
 * @param mixed $var 变量
 * @param boolean $echo 是否输出 默认为True 如果为false 则返回输出字符串
 * @param string $label 标签 默认为空
 * @param boolean $strict 是否严谨 默认为true
 * @return void|string
 */
function dp($var, $echo = true, $label = null, $strict = true)
{
    $label = ($label === null) ? '' : rtrim($label) . ' ';
    if (!$strict) {
        if (ini_get('html_errors')) {
            $output = print_r($var, true);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        } else {
            $output = $label . print_r($var, true);
        }
    } else {
        ob_start();
        var_dump($var);
        $output = ob_get_clean();
        if (!extension_loaded('xdebug')) {
            $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        }
    }
    if ($echo) {
        echo($output);
        return null;
    } else
        return $output;
}


function getPageNoList($totalPage, $pageNo, $pageSize)
{
    $disPageList = 0;//定义最大链接显示数额
    $disPageList = $pageNo + $pageSize - 1;//最大链接显示数额赋值，公式为"当前页数 + 最大链接显示数额 -1"
    //前页面导航页数
    $pageNoList = array();
    //循环显示出当前页面导航页数
    if ($disPageList <= $totalPage) {
        for ($i = $pageNo; $i <= $disPageList; $i++) {
            $pageNoList[] = $i;
        }
    } else {
        if ($totalPage < $pageSize) {
            for ($i = 1; $i <= $totalPage; $i++) {
                $pageNoList[] = $i;
            }
        } else {
            $start = $totalPage - $pageSize + 1;
            for ($i = $start; $i <= $totalPage; $i++) {
                $pageNoList[] = $i;
            }
        }
    }
    return $pageNoList;
}

function tolog($data, $myfile = '')
{
    is_array($data) ? $str = var_export($data, TRUE) : $str = $data;
    $myfile == '' ? $file = public_path('datalog.txt') : $file = $myfile;
    if ($myfile != '' && !file_exists($myfile)) {
        throw new Exception("Function < tolog > Error : The File Or The FilePath Is Not Exists !");
    }
    file_put_contents($file, $str . "\r\n", FILE_APPEND);
}

function unique_rand($min, $max, $num)
{
    $count = 0;
    $return = array();
    while ($count < $num) {
        $return[] = mt_rand($min, $max);
        $return = array_flip(array_flip($return));
        $count = count($return);
    }
    shuffle($return);
    return $return;
}

/**
 * @param $start_time
 * @param $end_time
 * 获取时间轴
 */
function getX($start_time, $end_time)
{
    $days[] = $start_time;
    while (strtotime($start_time) < strtotime($end_time)) {
        $start_time = date('Y-m-d', strtotime("+1 day $start_time"));
        $days[] = $start_time;
    }
    return $days;
}

/**
 * @param $year  给定的年份
 * @param $month 给定的月份
 * @param $legth 筛选的区间长度 取前六个月就输入6
 * @param int $page 分页
 * @return array
 */
function getLastTimeArea($year, $month, $legth, $page = 1)
{
    if (!$page) {
        $page = 1;
    }
    $monthNum = $month + $legth - $page * $legth;
    $num = 1;
    if ($monthNum < -12) {
        $num = ceil($monthNum / (-12));
    }
    $timeAreaList = [];
    for ($i = 0; $i < $legth; $i++) {
        $temMonth = $monthNum - $i;
        $temYear = $year;
        if ($temMonth <= 0) {
            $temYear = $year - $num;
            $temMonth = $temMonth + 12 * $num;
            if ($temMonth <= 0) {
                $temMonth += 12;
                $temYear -= 1;
            }
        }
        $startMonth = strtotime($temYear . '/' . $temMonth . '/01');//该月的月初时间戳
        $endMonth = strtotime($temYear . '/' . ($temMonth + 1) . '/01') - 1;//该月的月末时间戳
        $res['date'] = $temYear . '年' . $temMonth . '月'; //该月的月初格式化时间
        $res['startMonth'] = $temYear . '/' . $temMonth . '/01'; //该月的月初格式化时间
        $res['endMonth'] = date('Y/m/d', $endMonth);//该月的月末格式化时间
        $res['timeArea'] = implode(',', [$startMonth, $endMonth]);//区间时间戳
        $timeAreaList[] = $res;
    }
    return $timeAreaList;
}

/**
 *上传多图  仅限 base64
 *
 * @param $imgs
 * @param bool|false $dir 路径
 * @param bool|true $isdel
 * @return string
 */
function upImgs($imgs, $dir = false)
{
    $dir = $dir ? $dir : date('Ymd');
    $res = '';
    $imgpath = "upload/" . $dir;
    if (!is_array($imgs)) {
        $res = upload($imgs, $imgpath);
        return $res;
    }
    foreach ($imgs as $k => $v) {
        $res = [];
        if (file_exists($v)) {
            $res[$k] = $v;
        } else {
            $v = explode(',', $v);
            $save = upload($v, $imgpath);
            if ($save) {
                $res[$k] = $save;
            }
        }
    }
    return $res;
}

/**
 *上传图片  仅限 base64
 *
 * @param $imgs
 * @param bool|false $path 路径
 * @return string
 */
function upload($img, $path)
{
    $v = explode(',', $img);
    preg_match('/image\/(.*);base64/u', $v[0], $imgtype);
    $imgtype = $imgtype[1] == "jpeg" ? 'jpg' : $imgtype[1];
    if (!is_dir($path)) {
        mkdir($path);
    }
    list($usec, $sec) = explode(" ", microtime());
    $imgname = $sec . str_replace('0.', '_', $usec);
    $imgname = $imgname . '.' . $imgtype;
    $base64 = base64_decode(end($v));
    $res = file_put_contents($path . "/" . $imgname, $base64);
    if ($res) {
        return $path . "/" . $imgname;
    }
    return false;
}

function addSession($key, $value)
{
    session([$key => $value]);
}


/**
 * @param $url 请求网址
 * @param bool $params 请求参数
 * @param int $ispost 请求方式
 * @param int $https https协议
 * @return bool|mixed
 */
function apiCurl($apiName, $options = '', $dirurl = '', $ispost = 0, $https = 0)
{
    $httpInfo = array();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    if ($https) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
    }
    $api = config('api.' . $apiName);
    if (!$dirurl) {
        $url = 'http://155m5k1578.iask.in:30552/hisapp/?service=His.' . $apiName;
    } else {
        $url = $dirurl . "." . $apiName;
    }
    $params = '';
    if ($api['model_name']) {
        $model_name = '\App\Models\\' . ucfirst($api['model_name']);
        $model = new $model_name();
        if ($options) {
            $params = $model->$api['method']($options);
        } else {
            $params = $model->$api['method']();
        }
    }
    if ($ispost) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_URL, $url);
    } else {
        if ($params) {
            if (is_array($params)) {
                $params = http_build_query($params);
            }
//            dd($url . '&' . $params);
            curl_setopt($ch, CURLOPT_URL, $url . '&' . $params);
        } else {
            curl_setopt($ch, CURLOPT_URL, $url);
        }
    }

    $response = curl_exec($ch);
    if ($dirurl) {
        $res = json_decode($response);
        $res = object_array($res);
        return $res;
        die;
    }
    if ($response === FALSE) {
        //echo "cURL Error: " . curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
    curl_close($ch);
    $res = json_decode($response);
    $res = object_array($res);
    $data['msg'] = $api['desc'] . '接口出现错误！';
    if ($res['ret'] != 200) {
        $data['error'] = $res['msg'];
        dd($data);
    }
    if ($res['data']['code'] != 1) {
        $data['error'] = $res['data']['msg'];
        dd($data);
    }
    if (isset($res['data']['result']['Data']['Ie'])) {
        return $res['data']['result']['Data']['Ie'];
    } else {
        return $res;
    }
}

//$type  0.全天 1.上午 2.下午
function getTimeArea($type = 0)
{
    if ($type == 0) {
        return config('time');
    }
    if ($type == 1) {
        return array_slice(config('time'), 0, 7, true);
    }
    if ($type == 2) {
        return array_slice(config('time'), 7, -1, true);
    }
}

//获取星期方法
function get_week($date)
{
    //强制转换日期格式
    $date_str = date('Y-m-d', strtotime($date));

    //封装成数组
    $arr = explode("-", $date_str);

    //参数赋值
    //年
    $year = $arr[0];

    //月，输出2位整型，不够2位右对齐
    $month = sprintf('%02d', $arr[1]);

    //日，输出2位整型，不够2位右对齐
    $day = sprintf('%02d', $arr[2]);

    //时分秒默认赋值为0；
    $hour = $minute = $second = 0;

    //转换成时间戳
    $strap = mktime($hour, $minute, $second, $month, $day, $year);

    //获取数字型星期几
    $number_wk = date("w", $strap);

    //自定义星期数组
    $weekArr = array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");

    //获取数字对应的星期
    return $weekArr[$number_wk];
}

/**
 * 数组分页函数 核心函数 array_slice
 * 用此函数之前要先将数据库里面的所有数据按一定的顺序查询出来存入数组中
 * $count  每页多少条数据
 * $page  当前第几页
 * $array  查询出来的所有数组
 * order 0 - 不变   1- 反序
 */
function page_array($count, $page, $array, $order)
{
    global $countpage; #定全局变量
    $page = (empty($page)) ? '1' : $page; #判断当前页面是否为空 如果为空就表示为第一页面
    $start = ($page - 1) * $count; #计算每次分页的开始位置
    if ($order == 1) {
        $array = array_reverse($array);
    }
    $totals = count($array);
    $countpage = ceil($totals / $count); #计算总页面数
    $pagedata = array();
    $pagedata = array_slice($array, $start, $count);
    return $pagedata; #返回查询数据
}

/**
 * 保存文件到本地
 * @param 文件路径 $url
 * @param 保存路径 $path
 * @return string
 */
function downloadFile($url, $path)
{
    if (!is_dir($path)) {
        mkdir($path);
    }
    $ary = parse_url($url);
    $fileName = basename($ary['path']);
    $file = file_get_contents($url);
    file_put_contents($path . '/' . $fileName, $file);
    return $fileName;
}

/**
 * 获取文件扩展名
 * @param 网页URL $url
 * @return string
 */
function getUrlFileExt($url)
{
    $ary = parse_url($url);
    $file = basename($ary['path']);
    $ext = explode('.', $file);
    return $ext[1];
}

function GrabImage($url, $filename = "")
{
    if ($url == "") return false;
    if ($filename == "") {
        $ext = strrchr($url, ".");
        if ($ext != ".HOEMR") return false;
        $filename = date("dMYHis") . $ext;
    }

    ob_start();
    readfile($url);
    $img = ob_get_contents();
    ob_end_clean();
    $size = strlen($img);
    $fp2 = @fopen($filename, "a");
    fwrite($fp2, $img);
    fclose($fp2);
    return $filename;
}


/**
 * 分页及显示函数
 * $countpage 全局变量，照写
 * $url 当前url
 */
function show_array($countpage, $url)
{
    $page = empty($_GET['page']) ? 1 : $_GET['page'];
    if ($page > 1) {
        $uppage = $page - 1;
    } else {
        $uppage = 1;
    }
    if ($page < $countpage) {
        $nextpage = $page + 1;

    } else {
        $nextpage = $countpage;
    }
    $str = '<div style="border:1px; width:300px; height:30px; color:#9999CC">';
    $str .= "<span>共 {$countpage} 页 / 第 {$page} 页</span>";
    $str .= "<span><a href='$url?page=1'>  首页 </a></span>";
    $str .= "<span><a href='$url?page={$uppage}'> 上一页 </a></span>";
    $str .= "<span><a href='$url?page={$nextpage}'>下一页 </a></span>";
    $str .= "<span><a href='$url?page={$countpage}'>尾页 </a></span>";
    $str .= '</div>';
    return $str;
}

/**
 * 发送模板短信
 * @param to 手机号码集合,用英文逗号分开
 * @param datas 内容数据 格式为数组 例如：array('Marry','Alon')，如不需替换请填 null
 * @param $tempId 模板Id,测试应用和未上线应用使用测试模板请填写1，正式应用上线后填写已申请审核通过的模板ID
 */
function sendSMS($to, $datas, $tempId)
{
    // 初始化REST SDK
    $rest = new App\Support\Rest();
    // 发送模板短信
//    tolog("Sending TemplateSMS to $to <br/>");
    $result = $rest->sendTemplateSMS($to, $datas, $tempId);
    if ($result == NULL) {
//        tolog("result error!");
        return false;
    }
    if ($result->statusCode != 0) {
//        tolog("error code :" . $result->statusCode . "<br>");
//        tolog("error msg :" . $result->statusMsg . "<br>");
        return false;
    } else {
//        tolog("Sendind TemplateSMS success!<br/>");
        // 获取返回信息
        $smsmessage = $result->TemplateSMS;
//        tolog("dateCreated:".$smsmessage->dateCreated."<br/>");
//        tolog("smsMessageSid:".$smsmessage->smsMessageSid."<br/>");
        //TODO 添加成功处理逻辑
        return true;
    }
}

/**
 * 遍历文件夹删除
 * @param $path
 */
function remove($path)
{
    //2:将目录内容全部获取出
    $list = scandir($path);
    //3:遍历目录
    foreach ($list as $f) {
        //4:将 .  .. 排除在外
        if ($f != '.' && $f != '..') {
            //5:如果内容文件 unlink
            if (is_file($path . "/" . $f)) {
                unlink($path . "/" . $f);
            } else {
                $folders = scandir($path . "/" . $f);
                if (count($folders) == 2) {
                    rmdir($path . "/" . $f);
                } else {
                    //6:目录   递归
                    remove($path . "/" . $f);
                }
            }
        }
    }
}

/**
 * 获取客户端ip
 * @return string 当前IP地址
 */
function getIp()
{
    $onlineip = '';
    if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $onlineip = getenv('HTTP_CLIENT_IP');
    } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $onlineip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $onlineip = getenv('REMOTE_ADDR');
    } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $onlineip = $_SERVER['REMOTE_ADDR'];
    }
    return $onlineip;
}

/**
 * 验证邮箱
 * @param $email
 * @return bool
 */
function checkEmail($email)
{
    $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
    if (preg_match($pattern, $email)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 验证手机号支持以下号段
 *      移动：134、135、136、137、138、139、150、151、152、157、158、159、182、183、184、187、188、178(4G)、147(上网卡)；
 * 联通：130、131、132、155、156、185、186、176(4G)、145(上网卡)；
 * 电信：133、153、180、181、189 、177(4G)；
 * 卫星通信：1349
 * 虚拟运营商：170
 * @param $mobile
 * @return bool
 */
function checkMobile($mobile)
{
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
}

/**委托记录状态
 * @param $status  状态
 * @return string
 */
function getOrdersStatus($status)
{
    switch ($status) {
        case 0 :
            $data = "挂单";
            break;
        case 1 :
            $data = "部分成交";
            break;
        case 2 :
            $data = "成交";
            break;
        case -1 :
            $data = "已撤销";
            break;
        default:
            $data = "未知状态";
    }
    return $data;
}

/**委托记录type
 * @param $type
 * @return string
 */
function getOrdersType($type)
{
    switch ($type) {
        case "buy":
            $data = "买入";
            break;
        case "sell" :
            $data = "卖出";
            break;
        default:
            $data = "未知状态";
    }
    return $data;
}

///**
// * 导出数据为excel表格
// *
// * @param $data 一个二维数组,结构如同从数据库查出来的数组
// * @param $title excel的第一行标题,一个数组,如果为空则没有标题
// * @param $filename 下载的文件名
// *        	@examlpe
// *        	$stu = M ('User');
// *        	$arr = $stu -> select();
// *        	exportexcel($arr,array('id','账户','密码','昵称'),'文件名!');
// */
//function exportexcel($data = array(), $title = array(), $filename = 'report') {
//    header ( "Content-type:application/octet-stream" );
//    header ( "Accept-Ranges:bytes" );
//    header ( "Content-type:application/vnd.ms-excel" );
//    header ( "Content-Disposition:attachment;filename=" . $filename . ".xls" );
//    header ( "Pragma: no-cache" );
//    header ( "Expires: 0" );
//    // 导出xls 开始
//    if (! empty ( $title )) {
//        foreach ( $title as $k => $v ) {
//            $title [$k] = iconv ( "UTF-8", "GB2312", $v );
//        }
//        $title = implode ( "\t", $title );
//        echo "$title\n";
//    }
//    if (! empty ( $data )) {
//        foreach ( $data as $key => $val ) {
//            foreach ( $val as $ck => $cv ) {
//                $data [$key] [$ck] = iconv ( "UTF-8", "GB2312", $cv );
//            }
//            $data [$key] = implode ( "\t", $data [$key] );
//        }
//        echo implode ( "\n", $data );
//    }
//}

//充值状态格式化
function payStatus($num)
{
    switch ($num) {
        case 0:
            $data = "请付款";
            break;
        case 1:
            $data = "充值成功";
            break;
        case 2:
            $data = "充值失败";
            break;
        case 3:
            $data = "已失效";
            break;
        default:
            $data = "暂无";
    }
    return $data;
}

//提现状态格式化
function drawStatus($num)
{
    switch ($num) {
        case 0:
            $data = "未通过";
            break;
        case 1:
            $data = "未通过";
            break;
        case 2:
            $data = "通过";
            break;
        case 3:
            $data = "审核中";
            break;
        default:
            $data = "暂无";
    }
    return $data;
}

/**
 * 人民币格式化
 * @param $num
 * @return array|bool|string
 */
function num_format($num)
{
    if (!is_numeric($num)) {
        return false;
    }
    $rvalue = '';
    $num = explode('.', $num);//把整数和小数分开
    $rl = !isset($num['1']) ? '' : $num['1'];//小数部分的值
    $j = strlen($num[0]) % 3;//整数有多少位
    $sl = substr($num[0], 0, $j);//前面不满三位的数取出来
    $sr = substr($num[0], $j);//后面的满三位的数取出来
    $i = 0;
    while ($i <= strlen($sr)) {
        $rvalue = $rvalue . ',' . substr($sr, $i, 3);//三位三位取出再合并，按逗号隔开
        $i = $i + 3;
    }
    $rvalue = $sl . $rvalue;
    $rvalue = substr($rvalue, 0, strlen($rvalue) - 1);//去掉最后一个逗号
    $rvalue = explode(',', $rvalue);//分解成数组
    if ($rvalue[0] == 0) {
        array_shift($rvalue);//如果第一个元素为0，删除第一个元素
    }
    $rv = $rvalue[0];//前面不满三位的数
    for ($i = 1; $i < count($rvalue); $i++) {
        $rv = $rv . ',' . $rvalue[$i];
    }
    if (!empty($rl)) {
        $rvalue = $rv . '.' . $rl;//小数不为空，整数和小数合并
    } else {
        $rvalue = $rv;//小数为空，只有整数
    }
    return $rvalue;
}

/**
 * 验证邮箱
 * @param $email
 * @return bool
 */
function check_email($email)
{
    $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
    if (preg_match($pattern, $email)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @return mixed
 */
function get_ip($type = 0)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown', $arr);
        if (false !== $pos) unset($arr[$pos]);
        $ip = trim($arr[0]);
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * 根据众筹id号查找一共众筹次数
 * @param $id 用户ID
 * @return mixed 次数
 */
function getIssueMemberCountByIssueId($id)
{
    $re = \App\Models\IssueLog::where('iid', $id)->count("uid");
    if ($re) {
        return $re;
    } else {
        return 0;
    }
}

//格式化挂单买单还是卖单
function fomatOrdersType($type)
{
    switch ($type) {
        case 'buy':
            $type = '买';
            break;
        case 'sell':
            $type = '卖';
            break;
        default:
            $type = '无';
    }
    return $type;
}

/*
$to:邮件接收方
$title:邮件标题
$content:邮件内容
*/
function sendMail($to, $title, $content)
{
    $mail = new PHPMailer();
    // 设置为要发邮件
    $mail->IsSMTP();
    // 是否允许发送“HTML代码”做为邮件的内容
    $mail->IsHTML(TRUE);
    $mail->CharSet = 'UTF-8';
    // 是否需要身份验证
    $mail->SMTPAuth = TRUE;
    /*  邮件服务器上发送方账号设置 start*/
    $mail->From = ""; //发送方邮件地址
    $mail->FromName = "php7的主题邮件";  //发送方名称，会显示在邮件的内容中，可以自定义
    $mail->Host = "smtp.163.com";  //发送邮件的服务协议地址，中转邮件服务器地址
    $mail->Username = "";  //发送方帐号
    $mail->Password = ""; //发送方帐号密码
    /*  邮件服务器上发送方账号设置 end*/
    // 发邮件端口号默认25
    $mail->Port = 25;
    // 收件人
    $mail->AddAddress($to);
    // 邮件标题
//    $mail->Subject=$title;
    $mail->Subject = $title . "(" . date("Y-m-d H:i:s") . ")";
    // 邮件内容
    $mail->Body = $content;
    return ($mail->Send());//发送邮件

}

function setPostEmail($emailHost, $emailUserName, $emailPassWord, $formName, $email, $title, $body)
{
    $mail = new PHPMailer();//建立邮件发送类
    $mail->IsSMTP();//使用SMTP方式发送 设置设置邮件的字符编码，若不指定，则为'UTF-8
    $mail->Host = $emailHost;//'smtp.qq.com';//您的企业邮局域名
    $mail->SMTPAuth = true;//启用SMTP验证功能   设置用户名和密码。
    $mail->Username = $emailUserName;//'mail@koumang.com'//邮局用户名(请填写完整的email地址)
//    $mail->Username='admin@shikeh.com';//邮局用户名(请填写完整的email地址)
//    $mail->Password='WWW15988999998com';//邮局密码
    $mail->Password = $emailPassWord;//'xiaowei7758258'//邮局密码
    $mail->From = $emailUserName;//'mail@koumang.com'//邮件发送者email地址
    $mail->FromName = $formName;//邮件发送者名称
    $mail->AddAddress($email);// 收件人邮箱，收件人姓名
    //$mail->AddBCC('chnsos@126.com',$_SESSION['clean']['name']);//收件人地址，可以替换成任何想要接收邮件的email信箱,格式是AddAddress("收件人email","收件人姓名")
    $mail->IsHTML(true); // set email format to HTML //是否使用HTML格式
    $mail->Subject = "=?UTF-8?B?" . base64_encode($title) . "?=";
    $mail->Body = $body; //邮件内容
    $mail->AltBody = "这是一封HTML格式的电子邮件。"; //附加信息，可以省略
    return ($mail->Send());
//    return $mail->ErrorInfo;
}

function is_ajax()
{
    return ((isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') || !empty($_POST['ajax']) || !empty($_GET['ajax'])) ? true : false;
}

/**
 * 发送短信
 *
 * @param string $mobile 手机号码
 * @param string $name 短信头
 * @param string $user_name 短信账户
 * @param string $user_password 短息密码
 * @param string $needstatus 是否需要状态报告
 * @param string $product 产品id，可选
 * @param string $extno 扩展码，可选
 */
function sandPhone($mobile, $name, $user_name, $user_password, $needstatus = 'true', $product = '', $extno = '')
{
    $PORT = 80;//端口号默认80
    $IP = "222.73.117.156";
    $chuanglan_config['api_account'] = iconv('UTF-8', 'UTF-8', $user_name);
    $chuanglan_config['api_password'] = iconv('UTF-8', 'UTF-8', $user_password);
    $chuanglan_config['api_send_url'] = "http://" . $IP . ":" . $PORT . "/msg/HttpBatchSendSM";
    $code = rand(100000, 999999);
    session(['name' => 'code']);
    session(['code' => $code]);  //设置session
    session(['num' => session('num') + 1]);  //设置session
    session(['time' => time()]);

    /*if (session('num')>3){
            $arr[1]="121";
            return $arr;
     }*/

    $data = "您好，您的验证码是" . $code;//要发送的短信内容
    $content = mb_convert_encoding("$data", 'UTF-8', 'UTF-8');
    //创蓝接口参数
    $postArr = array(
        'account' => $chuanglan_config['api_account'],
        'pswd' => $chuanglan_config['api_password'],
        'msg' => $content,
        'mobile' => $mobile,
        'needstatus' => $needstatus,
        'product' => $product,
        'extno' => $extno
    );

    $result = curlPost($chuanglan_config['api_send_url'], $postArr);
    $result = execResult($result);
    return $result;
}

/**
 * 处理返回值
 *
 */
function execResult($result)
{
    $result = preg_split("/[,\r\n]/", $result);
    return $result;
}


/**
 * 通过CURL发送HTTP请求
 * @param string $url //请求URL
 * @param array $postFields //请求参数
 * @return mixed
 */
function curlPost($url, $postFields)
{
    $postFields = http_build_query($postFields);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    $result = curl_exec($ch);
    curl_close($ch);

    return $result;
}

function chuanglan_status($num)
{
    switch ($num) {
        case 0;
            $name = "短消息发送成功";
            break;
        case 101;
            $name = "无此用户";
            break;
        case 102;
            $name = "密码错";
            break;
        case 103;
            $name = "提交过快(提交速度超过流速限制)";
            break;
        case 104;
            $name = "系统忙（因平台侧原因，暂时无法处理提交的短信）";
            break;
        case 105;
            $name = "敏感短信（短信内容包含敏感词）";
            break;
        case 106;
            $name = "消息长度错（>536或<=0）";
            break;
        case 107;
            $name = "包含错误的手机号码";
            break;
        case 108;
            $name = "手机号码个数错（群发>50000或<=0;单发>200或<=0）";
            break;
        case 109:
            $name = "无发送额度（该用户可用短信数已使用完）";
            break;
        case 110:
            $name = "不在发送时间内";
            break;
        case 111:
            $name = "超出该账户当月发送额度限制";
            break;
        case 112:
            $name = "无此产品，用户没有订购该产品";
            break;
        case 113:
            $name = "extno格式错（非数字或者长度不对)";
            break;
        case 115:
            $name = "自动审核驳回";
            break;
        case 116:
            $name = "签名不合法，未带签名（用户必须带签名的前提下）";
            break;
        case 117:
            $name = "IP地址认证错,请求调用的IP地址不是系统登记的IP地址";
            break;
        case 118:
            $name = "用户没有相应的发送权限";
            break;
        case 119:
            $name = "用户已过期";
            break;
        case 120:
            $name = "短信内容不在白名单中";
            break;
        case 121:
            $name = "您已经超出短信发送次数限制";
            break;
        default:
            $name = "系统错误，请及时联系管理员";
            break;
    }
    return $name;

}


/**
 * 验证手机
 * @param $code
 * @return bool
 */
function checkPhoneCode($code)
{
    if (session('code') != $code) {
        return false;
    } else {
        return true;
    }
}

//委托状态格式化
function enstrustStatus($num)
{
    switch ($num) {
        case 0:
            $data = "未成交";
            break;
        case 1:
            $data = "部分成交";
            break;
        case 2:
            $data = "已成交";
            break;
        case 3:
            $data = "已撤销";
            break;
        case 4:
            $data = "全部";
            break;
        default:
            $data = "暂无";
    }
    return $data;
}

//充值状态格式化
function zhongchouStatus($num)
{
    switch ($num) {
        case 0:
            $data = "新众筹";
            break;
        case 1:
            $data = "众筹开始";
            break;
        case 2:
            $data = "众筹结束";
            break;
        case 3:
            $data = "众筹结束";
            break;
        default:
            $data = "暂无";
    }
    return $data;
}

/**
<<<<<<< HEAD
 * 格式化挂单记录status状态
 * @param unknown $status   状态
 * @return unknown
 */
function formatOrdersStatus($status){
    switch($status){
        case 0: $status = '未成交' ;break;
        case 1: $status = '部分成交' ;break;
        case 2: $status = '已成交' ;break;
        case -1: $status = '已撤销' ;break;
        default: $status = '未成交' ;break;
    }
    return  $status;
}
/*
 * 格式化用户名
 * @param unknown $currency_id   币种id
 * @return unknown
 */
function getCurrencynameByCurrency($currency_id){
    if(isset($currency_id)){
        if($currency_id==0){
            return "人民币";
        }
        $result = \App\Models\Currency::where("currency_id",$currency_id)->first();
        return $result['currency_name'];
    }else{
        return "未知钱币";
    }
}
?>
